<template>
  <div class="body">
    <div class="main-box">
      <div :class="['container', 'container-login', { 'is-txl is-z200': isLogin }]">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules">
          <h3 class="title">科研服务管理平台</h3>
          <div class="el-item-input">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" :prefix-icon="User"
                placeholder="账号">
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off"
                :prefix-icon="Lock" placeholder="密码" @keyup.enter="handleLogin">
              </el-input>
            </el-form-item>
          </div>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input v-model="loginForm.code" size="large" auto-complete="off" :prefix-icon="Key" placeholder="验证码"
              style="width: 63%" @keyup.enter="handleLogin">
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" @error="getCode" />
            </div>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <!-- <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'" :prefix-icon="Pointer">立即注册</router-link>
          </div> -->
          </el-form-item>
        </el-form>
      </div>
      <div :class="['switch', { 'login': isLogin }]">
        <div class="switch__circle"></div>
        <div class="switch__circle switch__circle_top"></div>
        <div class="switch__container">
          <div class="image-container">
            <img src="/public/titleImg.png" alt="Title Image" class="title-image" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from '@/store/user.js';
import { ref, getCurrentInstance, onMounted } from 'vue';
import { getVerifyCode, login } from "@/api/auth";
import { useRouter } from 'vue-router';
import { User, Lock, Key } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import { userTokenStore } from "../store/token.js";
import { cartListUser } from '@/api/user';

const store = useStore();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  code: ""
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const captchaKey = ref("");
const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);
const register = ref(true);

async function handleLogin() {
  proxy.$refs.loginRef.validate(async valid => {
    console.log("表单校验结果:", valid); // 调试日志
    if (valid) {
      loading.value = true;
      try {
        const credentials = {
          username: loginForm.value.username,
          password: loginForm.value.password,
          code: captchaEnabled.value ? loginForm.value.code : '',
          captchaKey: captchaEnabled.value ? captchaKey.value : '',
        };

        try {
          const response = await login(credentials);
          console.log("后端返回数据:", response);

          const responseData = response;
          console.log("解析后的数据:", responseData);

          let role = null; // 提前声明 role
          if (responseData && responseData.data && responseData.data.role) {
            role = responseData.data.role; // 赋值
            console.log("用户角色:", role);

            ElMessage.success(responseData.message || "登录成功");

            // 获取当前登录用户信息
            const response = await cartListUser(responseData.data.token); // 调用正确的 API 方法
            // 更新 Pinia 状态
            const userStore = useUserStore();
            userStore.setUser({
              userId: response.userId,
              username: response.username,
              token: response.token,
            });


            // 在登录成功后存储token
            const tokenStore = userTokenStore();
            tokenStore.setToken(`Bearer ${responseData.data.token}`);
            console.log("存储token:", tokenStore);
            // const tokenStore = userTokenStore();
            // // 确保token格式正确
            // tokenStore.setToken(`Bearer ${responseData.token}`);

            try {
              router.push({
                path: getRedirectPath(role),
              });
            } catch (error) {
              console.error("路由跳转失败:", error);
              ElMessage.error("跳转页面失败，请稍后重试");
            }
          } else {
            ElMessage.error("登录失败：返回数据格式不正确");
          }
        } catch (error) {
          console.error("登录请求失败:", error);
          ElMessage.error("登录失败，请稍后重试");
        }
      } finally {
        loading.value = false;
      }
    }
  });
}



function getRedirectPath(role) {
  switch (role) {
    case "超级管理员":
      return '/adminIndex/user';
    case '普通用户':
      return '/userIndex/personal';
    case '二级学院管理员':
      return '/twoAdminIndex/twoUser';
    default:
      return '/login';
  }
}

// // 获取当前登录用户信息
// const fetchCurrentUser = async () => {
//   try {
//     const response = await cartListUser(); // 调用正确的 API 方法
// // 更新 Pinia 状态
// const userStore = useUserStore();
//   userStore.setUser({
//     userId: response.data.userId,
//     username: response.data.username,
//     token: response.data.token,
//   });

//   } catch (error) {
//     console.error('Failed to fetch user info:', error);
//   }
// };

async function getCode() {
  try {
    const result = await getVerifyCode();
    if (result && result.url) {
      codeUrl.value = result.url;
      captchaKey.value = result.captchaKey;
    } else {
      ElMessage.error('获取验证码失败，请刷新重试');
    }
  } catch (error) {
    ElMessage.error('获取验证码失败，请刷新重试');
  }
}


onMounted(() => {
  getCode();
});
</script>

<style lang="scss" scoped>
@import '../assets/css/app.css';
@import '../assets/css/chunkcss.css';

.body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "Montserrat", sans-serif;
  font-size: 12px;
  background-image: url("@/assets/images/background.jpg");
  color: #a0a5a8;

}

.main-box {
  position: relative;
  width: 1000px;
  min-width: 1000px;
  min-height: 600px;
  height: 600px;
  padding: 25px;
  background-color: #ecf0f3;
  box-shadow: 1px 1px 100px 10PX #ecf0f3;
  border-radius: 12px;
  overflow: hidden;

  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    width: 600px;
    height: 100%;
    padding: 25px;
    background-color: #ecf0f3;
    transition: all 1.25s;

    form {

      .title {
        font-size: 28px;
        // font-weight: 700;
        line-height: 3;
        margin: 0px auto 30px auto;
        text-align: center;
        color: #707070;
      }

      .text {
        margin-top: 30px;
        margin-bottom: 12px;
      }

    }
  }

  .container-register {
    z-index: 100;
    left: calc(100% - 600px);
  }

  .container-login {
    left: calc(100% - 600px);
    z-index: 0;
  }

  .is-txl {
    left: 0;
    transition: 1.25s;
    transform-origin: right;
  }

  .is-z200 {
    z-index: 200;
    transition: 1.25s;
  }

  .switch {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 400px;
    padding: 50px;
    z-index: 200;
    transition: 1.25s;
    background-color: #ecf0f3;
    overflow: hidden;
    box-shadow: 4px 4px 10px #d1d9e6, -4px -4px 10px #f9f9f9;
    color: #a0a5a8;

    .switch__circle {
      position: absolute;
      width: 500px;
      height: 500px;
      border-radius: 50%;
      background-color: #ecf0f3;
      box-shadow: inset 8px 8px 12px #d1d9e6, inset -8px -8px 12px #f9f9f9;
      bottom: -60%;
      left: -60%;
      transition: 1.25s;
    }

    .switch__circle_top {
      top: -30%;
      left: 60%;
      width: 300px;
      height: 300px;
    }

    .switch__container {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      position: absolute;
      width: 400px;
      padding: 50px 55px;
      transition: 1.25s;

      h2 {
        font-size: 34px;
        font-weight: 700;
        line-height: 3;
        color: #181818;
      }

      p {
        font-size: 14px;
        letter-spacing: 0.25px;
        text-align: center;
        line-height: 1.6;
      }
    }
  }

  .login {
    left: calc(100% - 400px);

    .switch__circle {
      left: 0;
    }
  }

  .form__button {
    width: 180px;
    height: 50px;
    border-radius: 25px;
    margin-top: 50px;
    text-align: center;
    line-height: 50px;
    font-size: 14px;
    letter-spacing: 2px;
    background-color: #4b70e2;
    color: #f9f9f9;
    cursor: pointer;
    box-shadow: 8px 8px 16px #d1d9e6, -8px -8px 16px #f9f9f9;

    &:hover {
      box-shadow: 2px 2px 3px 0 rgba(255, 255, 255, 50%),
        -2px -2px 3px 0 rgba(116, 125, 136, 50%),
        inset -2px -2px 3px 0 rgba(255, 255, 255, 20%),
        inset 2px 2px 3px 0 rgba(0, 0, 0, 30%);
    }
  }
}



.title-image {
  width: 200px;
  /* 增大图片大小 */
  height: auto;
  border-radius: 50%;
  /* 圆形图片 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 添加阴影 */
  margin-left: -38px;
  margin-top: -15px;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 40px;
  width: 117px;
  margin-left: 12px;
  border: 1px solid #1890ff;
}

.el-input__inner {
  margin-left: -16px;
}

.el-item-input {
  width: 362px;

  :deep(.el-input) {
    width: 100% !important;
  }

  :deep(.el-input__wrapper) {
    width: 100% !important;
  }
}
</style>